<script setup>
import { computed, reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, dayjs } from 'element-plus'
import * as XLSX from 'xlsx'

const levelOpts = ref([])
async function handleGetLevelOpts() {
  const res = await window.api.getAllDealerLevel()
  console.log(res)
  levelOpts.value = res
}
handleGetLevelOpts()

const filterState = reactive({
  time: '',
  name: '',
  level: ''
})

const tableCols = [
  {
    key: 'parent_dealer_name',
    label: '绑定关系'
  },
  {
    key: 'dealer_name',
    label: '经销商名称'
  },
  {
    key: 'dealer_level_name',
    label: '经销商等级'
  },
  {
    key: 'money',
    label: '团队业绩',
    sort: true
  },
  {
    key: 'rate',
    label: '分红比例(%)'
  },
  {
    key: 'dividendMoney',
    label: '分红奖金（元）'
  }
]
// 团队业绩总计
const teamMoneyCount = computed(() => {
  let count = 0

  listState.list.forEach((item) => {
    if (!listState.list.some((i) => i.dealer_id === item.parent_dealer_id)) {
      count += Number(item.money)
    }
  })

  return count
})
// 分红奖金总计
const dividendMoneyCount = computed(() => {
  let count = 0
  // const arr = listState.list.filter((i) => i.parent_dealer_id)
  // arr.forEach((item) => {
  //   if (!listState.list.some((i) => i.dealer_id === item.parent_dealer_id)) {
  //     count += Number(item.dividendMoney)
  //   }
  // })
  listState.list.forEach((item) => {
    count += Number(item.dividendMoney)
  })

  return count
})

const listState = reactive({
  page: 1,
  pageSize: 20000000,
  list: [],
  totals: 0,
  loading: false
})
// 获取有效的分红规则
let dividendRule = []
async function getDividendRule() {
  const res = await window.api.getDividendByIsEnable(1)
  console.log('分红规则数据', res)
  let rules = res[0] || []
  if (!rules) return
  dividendRule = await window.api.getDividendDetail(rules.dividend_id)
  getDividendList()
}
getDividendRule()
async function getDividendList() {
  if (!dividendRule.length) {
    ElMessage.warning('未配置有效分红规则')
    return
  }
  console.log('分红规则', dividendRule)
  listState.loading = true
  const res = await window.api.getDealerList(
    listState.pageSize,
    listState.page - 1,
    // filterState.time?.[0] || '',
    // filterState.time?.[1] || '',
    filterState.level,
    filterState.name
  )
  console.log('getDividendList:', res)
  setTimeout(() => {
    listState.loading = false
  }, 500)
  let arr = res.rows || []
  listState.total = res.total || 0
  console.log('getDividendListArr', arr)
  // 获取等级 用于下面判断该进销商是否有分红
  const resLevel = await window.api.getAllDealerLevel()
  // 去除掉不分红的人
  arr=arr.filter(_item=>resLevel.some((i) => i.dealer_level_id === _item.dealer_level_id && i.is_dividend))
  listState.total=arr.length

  const promises = arr.map(async (item) => {
    item.money = 0
    item.rate = ''
    item.dividendMoney = 0
    const pArr = await window.api.getPerformanceRecordByDealerForDate(
      item.dealer_id,
      filterState.time?.[0] || '',
      filterState.time?.[1] || ''
    )
    pArr.forEach((i) => {
      item.money += i.team_money
    })

    item.money = Number(item.money).toFixed(2)
    //判断该等级是否分红
    if (
      item.parent_dealer_id !== 0 &&
      resLevel.some((i) => i.dealer_level_id === item.dealer_level_id && i.is_dividend)
    ) {
      let temRewardNum = 0 //算奖金的团队业绩
      //获取下该用户是否有等级变更
      const changeLevelRes = await window.api.getDealerLevelChangeRecord(item.dealer_id)
      let changeDate = changeLevelRes[0]?.change_date
      console.log('等级变更的日期', changeDate)
      if (changeDate) {
        pArr.forEach((_i) => {
          if (dayjs(dayjs(_i.performance_date)).isAfter(dayjs(changeDate))) {
            temRewardNum += _i.team_money
          }
        })
      } else {
        temRewardNum = item.money
      }
      // 计算奖金
      if (dividendRule) {
        dividendRule.forEach((_r) => {
          if (temRewardNum < _r.end_money && temRewardNum >= _r.start_money) {
            console.log(temRewardNum, _r.ratio)
            item.rate = _r.ratio
            item.dividendMoney = (temRewardNum * _r.ratio) / 100
          }
        })
      }
      // // 查询分红比例的值
      // if (dividendRule) {
      //   dividendRule.forEach((_r) => {
      //     if (
      //       Number(item.money) < Number(_r.end_money) &&
      //       Number(item.money) >= Number(_r.start_money)
      //     ) {
      //       item.rate = _r.ratio
      //     }
      //   })
      // }
      // //计算分红奖金
      // item.dividendMoney = Number(item.money) > 0 ? (item.rate * Number(item.money)) / 100 : 0
      // item.dividendMoney = Number(item.dividendMoney).toFixed(2)
    }

    return item
  })
  const dataArr = await Promise.all(promises)

  listState.list = dataArr
}

function changePageNo(page) {
  listState.page = page
  getDividendList()
}
function handleRefreshList() {
  getDividendList()
}
function handleSortChange(e) {
  console.log(e)
}

function handelExportData() {
  // const listData=[]

  // 设置 Excel 表头
  const headers = [
    '绑定关系',
    '经销商名称',
    '经销商等级',
    '团队业绩',
    '分红比例(%)',
    '分红奖金（元）'
  ]

  // 将 listData 转换为合适的格式，每项数据对应 '姓名'、'年龄'、'性别'
  const processedData = listState.list.map((item) => ({
    绑定关系: item.parent_dealer_name,
    经销商名称: item.dealer_name,
    经销商等级: item.dealer_level_name,
    团队业绩: item.money,
    '分红比例(%)': item.rate,
    '分红奖金（元）': item.dividendMoney
  }))

  // 使用 XLSX.utils.json_to_sheet 生成 sheet，添加表头
  const ws = XLSX.utils.json_to_sheet(processedData, { header: headers })

  // 创建新的工作簿
  const wb = XLSX.utils.book_new()
  // 将 sheet 添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 导出 Excel 文件
  XLSX.writeFile(wb, `分红列表${dayjs().format('YYYYMMDD')}.xlsx`)
}
</script>

<template>
  <div class="dividend-list-page">
    <div class="top-filter-wrap">
      <div style="width: 350px">
        <el-date-picker
          v-model="filterState.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </div>
      <el-input
        v-model="filterState.name"
        placeholder="请输入经销商名称"
        style="width: 200px"
        :prefix-icon="Search"
      ></el-input>
      <el-select
        v-model="filterState.level"
        clearable
        placeholder="请选择经销商等级"
        style="width: 200px"
      >
        <el-option
          v-for="item in levelOpts"
          :key="item.dealer_level_id"
          :label="item.dealer_level_name"
          :value="item.dealer_level_id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="handleRefreshList">查询</el-button>
      <el-button type="primary" @click="handelExportData">导出</el-button>
    </div>

    <div class="count-box">
      <span>团队业绩：{{ formatPrice(teamMoneyCount) }}元</span>
      <span>总人数：{{ listState.total }}人</span>
      <span>分红奖金：{{ formatPrice(dividendMoneyCount) }}元</span>
    </div>

    <div v-loading="listState.loading" class="table-wrap">
      <el-table
        :data="listState.list"
        max-height="1000"
        style="width: 100%"
        border
        @sort-change="(event) => handleSortChange(event)"
      >
        <el-table-column
          v-for="item in tableCols"
          :key="item.key"
          :prop="item.key"
          :label="item.label"
          align="center"
          :width="item.width"
          :sortable="item.sort ? true : false"
        >
        </el-table-column>
        <template #empty>
          <div class="table-no-data">
            <img src="@renderer/assets/img/empty-data.png" />
            <span>暂无数据</span>
          </div>
        </template>
      </el-table>
      <!-- <mPage
        :page-size="listState.pageSize"
        :page_no="listState.page"
        style="display: flex; justify-content: flex-end; margin-top: 20px"
        :total="listState.total"
        @handle-current-change="changePageNo"
      /> -->
    </div>
  </div>
</template>

<style lang="scss" scoped>
.dividend-list-page {
  .count-box {
    margin-top: 20px;
    margin-bottom: 20px;
    span {
      display: inline-block;
      margin-right: 20px;
    }
  }
}
</style>
